<!--校门时间段管理-->

<template>
  <div class="log">
    <basic-container>
      <el-row :span="24">
        <el-col :span="15">
          <el-form v-model="editform" style="padding-left: 20px">
            <h3 style="display: inline-block">时间组</h3>
            <p style="display: inline-block;margin:10px 20px 0 54px;">该时间组绑定人数：<span style="font-weight: bold">{{this.getPlanCount}}人</span></p>
            <el-button type="warning" @click.native="outdetails">点击查看</el-button>
            <el-form-item label="时间组名称" prop="timePlanName">
              <el-input v-model="editform.timePlanName" style="width: 55%;margin-left: 28px"></el-input>
            </el-form-item>
            <el-form-item label="时间组生效日期" prop="validTime">
              <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :clearable="false"
                  style="width: 55%">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="时间状态" prop="states">
              <el-radio v-model="editform.states" :label="0" :value="0" style="margin-left: 44px">正常</el-radio>
              <el-radio v-model="editform.states" :label="1" :value="1">停用</el-radio>
            </el-form-item>
            <el-form-item label="高三级时间组" prop="isThirdGrade">
              <el-radio v-model="editform.isThirdGrade" :label="0" :value="0" style="margin-left: 14px">是</el-radio>
              <el-radio v-model="editform.isThirdGrade" :label="1" :value="1">否</el-radio>
            </el-form-item>
          </el-form>
          <h3 style="margin-left: 16px">已选时间段</h3>
          <avue-crud
              ref="crud"
              :data="SelectedData"
              :option="SelectedOption"
              @on-load="getListSelect"
              @row-del="handleDel">
            <template slot="timerange" slot-scope="scope">
              {{ scope.row.timeFrameStart.substr(0,5) }}-{{ scope.row.timeFrameEnd.substr(0,5) }}
            </template>
            <template slot="weeks" slot-scope="scope">
              <el-checkbox-group v-model="scope.row.weeks">
                <el-checkbox-button label="1" value="周一">周一</el-checkbox-button>
                <el-checkbox-button label="2" value="周二">周二</el-checkbox-button>
                <el-checkbox-button label="3" value="周三">周三</el-checkbox-button>
                <el-checkbox-button label="4" value="周四">周四</el-checkbox-button>
                <el-checkbox-button label="5" value="周五">周五</el-checkbox-button>
                <el-checkbox-button label="6" value="周六">周六</el-checkbox-button>
                <el-checkbox-button label="7" value="周日">周日</el-checkbox-button>
              </el-checkbox-group>

            </template>
            <template slot="directions" slot-scope="scope">
              <el-checkbox-group v-model="scope.row.directions" class="direction">
                <el-checkbox-button label="0" value="进">进</el-checkbox-button>
                <el-checkbox-button label="1" value="出">出</el-checkbox-button>
              </el-checkbox-group>
            </template>
            <template slot="menu" slot-scope="scope">
              <el-button
                  class="filter-item"
                  size="mini"
                  type="danger"
                  @click="handleDel(scope.row)">删除
              </el-button>
            </template>
          </avue-crud>
          <el-form v-model="editform" style="padding-left: 20px">
            <h3 style="color: #000;">绑定优先特殊时间段</h3>
            <p style="font-size: 14px;color: red;margin: 10px 0">此项为非必填项,特殊时间段通行优先级大于时间组别内通行权限,且仅可设置一个</p>
            <el-form-item label="生效日期" prop="validTime">
              <el-date-picker
                  v-model="beforedateRange"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  style="width: 55%;margin-left: 40px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="时间范围" prop="timeRange">
              <el-time-picker
                  v-model="beforetimeRange"
                  end-placeholder="结束时间"
                  format="HH:mm"
                  is-range
                  placeholder="选择时间范围"
                  range-separator="-"
                  start-placeholder="开始时间"
                  value-format="HH:mm:ss"
                  style="width: 55%;margin-left: 40px">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="通行方向" prop="beforeDirections">
              <el-checkbox-group v-model="beforeDirections">
                <el-checkbox style="margin-left: 40px" label="0">进</el-checkbox>
                <el-checkbox label="1">出</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </el-col>

        <el-col :span="8" style="float: right">
          <avue-crud
              ref="crud"
              :data="tableData"
              :option="tableOption"
              @on-load="getList">
            <template slot="timerange" slot-scope="scope">
              {{ scope.row.timeFrameStart.substr(0, 5) }}-{{ scope.row.timeFrameEnd.substr(0, 5) }}
            </template>
            <template slot="status" slot-scope="scope">
              <el-tag v-if="scope.row.status === 0">正常</el-tag>
              <el-tag v-if="scope.row.status === 1" type="danger">停用</el-tag>
            </template>
            <template slot="menu" slot-scope="scope">
              <el-button v-if="scope.row.flag === true" class="filter-item" size="mini" type="primary"
                         @click="choice(scope.row)">选择
              </el-button>
              <el-button v-else-if="scope.row.flag === false" disabled size="mini" type="primary">已选</el-button>
            </template>
          </avue-crud>
        </el-col>
        <el-col style="text-align: center">
          <el-button class="filter-item" size="small" @click="dictItemVisible()">取消</el-button>
          <el-button class="filter-item" size="small" type="primary" @click="handleUpdate()">保存</el-button>
        </el-col>
      </el-row>
    </basic-container>
  </div>
</template>

<script>
import {timeFrame} from '@/api/pass/timeframe'
import {AddtimeframePlan, EdittimePlan, timeEdit, timeplanObj} from '@/api/pass/time-edit'
import {timegroupObj} from '@/api/pass/s-newtimegroup'

export default {
  name: 'outTime-edit',
  data() {
    return {
      getPlanCount:'',
      timeRange: '',
      dateRange: '',
      beforedateRange: '',
      beforetimeRange: '',
      directions: [],
      beforeDirections:[],
      dialogFormVisible: false,      //新增弹窗
      dialogEditVisible: false,
      tableData: [],
      SelectedData: [],
      tableLoading: false,
      editform: {
        timePlanName: '',
        timerange: '',
        states: '',
        isThirdGrade:'',
        validTimeStart: '',
        validTimeEnd: '',
        beforeDateStart: '',
        beforeDateEnd: ''
      },
      rules: {  //必填项（验证规则）
        states: [
          {required: true, trigger: "none"}
        ],
        timePlanName: [
          {required: true, trigger: "none"}
        ],
        validTime: [
          {required: true, trigger: "none"}
        ],
      },
      SelectedOption: {
        border:true,
        menuAlign: 'center',
        menuType: 'button',
        align: 'center',
        menuWidth:80,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        columnBtn: false,
        refreshBtn: false,
        maxHeight: 285,
        props: {
          label: 'label',
          value: 'value'
        },
        column: [
          {
            label: '时间段名',
            prop:'timeName',
          },
          {
            label: '时间范围',
            prop: 'timerange',
            slot: true,
          },
          {
            label: '生效日',
            prop: 'weeks',
            width: 415,
            slot: true,
          },
          {
            label: '进出属性',
            prop: 'directions',
            width: 110,
            slot: true,
          }
        ]
      },
      tableOption: {
        border:true,
        menuAlign: 'center',
        menuType: 'button',
        menuWidth:80,
        align: 'center',
        addBtn: false,
        editBtn: false,
        delBtn: false,
        columnBtn: false,
        refreshBtn: false,
        maxHeight: 730,
        props: {
          label: 'label',
          value: 'value'
        },
        column: [

          {
            label: '时间段名',
            prop: 'timeName',
          },
          {
            label: '时间范围',
            prop: 'timerange',
            slot: true,
          },
          {
            label: '状态',
            prop: 'status',
            slot: true
          }
        ]
      }
    }
  },
  computed: {},
  mounted() {
    this.getEditList()
  },
  methods: {
    outdetails() {
      const src = `/pass/outDetails`
      this.$router.push({
        path: src,
        query: {id: this.$route.query.id,
          timePlanName: this.editform.timePlanName,}
      })
    },

    //  获取时间组数据
    getEditList(row) {
      let param = this.$route.query;
      timeplanObj(param.id).then(res => {
        if (res.data.code === 0) {
          this.editform = res.data.data
          var datearr = []
          datearr.push(this.editform.validTimeStart, this.editform.validTimeEnd)
          this.dateRange = datearr
          //  获取特殊日期和时间
          if (this.editform.beforeDateStart !== null){
            var beforeDatearr = []
            beforeDatearr.push(this.editform.beforeDateStart, this.editform.beforeDateEnd)
            this.beforedateRange = beforeDatearr
            var beforeTimearr = []
            beforeTimearr.push(this.editform.beforeTimeStart, this.editform.beforeTimeEnd)
            this.beforetimeRange = beforeTimearr
            var beforeStr = this.editform.beforeDirection.toString()
            if(beforeStr === "2"){
              return this.beforeDirections = ["0","1"]
            }
            this.beforeDirections = beforeStr.split("");
          }
        }
      })

      let id = {
        timePlanGateId: param.id
      }
      timegroupObj(id).then(res =>{
        if (res.data.code === 0) {
          this.getPlanCount = res.data.data.total
        }
      })
    },
    // 获取已选时间段数据
    getListSelect() {
      this.tableLoading = true
      let param = this.$route.query;
      let params = {
        timePlanId: param.id
      }
      timeEdit(params).then(res => {
        if (res.data.code === 0) {
          this.SelectedData = res.data.data
          this.SelectedData.map(item => {
            this.$set(item, 'flag')
            item.flag = false
            this.$set(item, 'id')
            item.id = item.timeFrameId
            this.$set(item, 'weeks')
            item.weeks = item.week.split(",")
            this.$set(item, 'directions')
            var str = item.direction.toString()
            if(str === "2"){
              return item.directions = ["0","1"]
            }
            item.directions = str.split("");
          })
          this.tableData.forEach(item => {
            this.SelectedData.forEach(selected => {
              if (item.id === selected.timeFrameId) {
                item.flag = false
              }
            })
          })
        }
        this.tableLoading = false
      })
    },
    //  删除已选时间段
    handleDel: function (row) {
      this.$confirm('是否确认删除所选时间段？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let selectarr = this.SelectedData
        for (var i = 0; i < selectarr.length; i++) {
          if (selectarr[i].id === row.id) {
            selectarr.splice(i, 1);
            this.tableData.forEach(item => {
              if (item.id === row.id) {
                item.flag = true
              }
            })
          }
        }
        this.$message.success('删除成功')
      })
    },
    //  所有时间段数据
    getList(page, params,row) {
      timeFrame(Object.assign({
        descs: 'create_time',  //是否倒序
        size: 999
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.tableData.map(item => {
          this.$set(item, 'flag')
          item.flag = true
        })
        this.tableData.forEach(item => {
          this.SelectedData.forEach(selected => {
            if (item.id === selected.timeFrameId) {
              item.flag = false
            }
          })
        })
      })
      this.tableLoading = false
    },
    //  选择时间段
    choice: function (row) {
      this.SelectedData.push(row)
      this.SelectedData.map(item => {
        if (item.weeks === undefined || item.directions === undefined) {
          this.$set(item, 'weeks')
          this.$set(item, 'directions')
          item.weeks = []
          item.directions = []
        }
      })
      if (row.flag === true) {
        return row.flag = false
      }
    },

    //  保存编辑数据
    handleUpdate: function (row, done) {
      //校验
      if (this.editform.timePlanName === ''){
        this.$message.error('请输入时间组名称')
        return;
      }
      if (this.dateRange.length <= 0){
        this.$message.error('请选择时间组生效日期')
        return;
      }
      if (this.editform.states === ''){
        this.$message.error('请选择时间状态')
        return;
      }
      if (this.editform.isThirdGrade === ''){
        this.$message.error('请选择高三级时间组')
        return;
      }
      if (this.SelectedData.length <= 0){
        this.$message.error('请添加时间段')
        return;
      }
      if (this.SelectedData.length !== 0){
        for (var i = 0; i < this.SelectedData.length; i++){
          if (this.SelectedData[i].weeks.length <= 0){
            this.$message.error('请选择生效日')
            return;
          }
          if (this.SelectedData[i].directions.length <= 0){
            this.$message.error('请选择进出向')
            return;
          }
        }
      }
      let item = false
      let item1 = false
      let item2 = false
      if (this.beforedateRange === null){
        item = false
      }else {
        if (this.beforedateRange.length > 0){
          item = true
        }else {
          item = false
        }
      }

      if (this.beforetimeRange === null){
        item1 = false
      }else {
        if (this.beforetimeRange.length > 0){
          item1 = true
        }else {
          item1 = false
        }
      }

      if (this.beforeDirections.length > 0){
        item2 = true
      }else {
        item2 = false
      }
      if (item && item1 && item2){
        //date
        this.editform.beforeDateStart = this.beforedateRange[0]
        this.editform.beforeDateEnd = this.beforedateRange[1]
        //time
        this.editform.beforeTimeStart = this.beforetimeRange[0]
        this.editform.beforeTimeEnd = this.beforetimeRange[1]
        //dir
        if (this.beforeDirections.length > 1) {
          this.beforeDirections = ["2"]
        }
        this.editform.beforeDirection = this.beforeDirections.toString()
      }else if (!item && !item1 && !item2){
        this.editform.beforeDateStart = null
        this.editform.beforeDateEnd = null
        //time
        this.editform.beforeTimeStart = null
        this.editform.beforeTimeEnd = null
        //dir
        this.editform.beforeDirection = null
      }else {
        this.$message.error('请完整填写特殊时间段所有属性')
        return;
      }
      this.editform.validTimeStart = this.dateRange[0]
      this.editform.validTimeEnd = this.dateRange[1]
      // debugger
      // if (this.beforedateRange === null){
      //   this.editform.beforeDateStart = null
      //   this.editform.beforeDateEnd = null
      // }else {
      //   this.editform.beforeDateStart = this.beforedateRange[0]
      //   this.editform.beforeDateEnd = this.beforedateRange[1]
      // }
      // if (this.beforetimeRange === null){
      //   this.editform.beforeTimeStart = null
      //   this.editform.beforeTimeEnd = null
      // }else {
      //   this.editform.beforeTimeStart = this.beforetimeRange[0]
      //   this.editform.beforeTimeEnd = this.beforetimeRange[1]
      // }
      // if (this.beforeDirections.length > 1) {
      //   this.beforeDirections = ["2"]
      // }
      // this.editform.beforeDirection = this.beforeDirections.toString()
      this.editform.timeType = 0
      if (this.editform.states === 1){
        this.$confirm('停用时间组后，相关人员通行权限即时失效', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          EdittimePlan(this.editform).then(res => {
            if (res.data.code === 0) {
              this.SelectedData.forEach((value, index) => {
                value.weeks.sort()
                value['week'] = value.weeks.toString()
                value['timePlanId'] = this.editform.id
                value.timeFrameId = value.id
                // value.directions.sort()
                if (value.directions.length > 1) {
                  value.directions = ["2"]
                }
                value['direction'] = value.directions.toString()
              })
              AddtimeframePlan(this.SelectedData).then(res => {
                if (res.data.code === 0) {
                  this.$message.success('修改成功')
                }
                this.$router.go(-1)
              })
            } else {
              this.$message.error('修改失败')
            }
          })
        })
      }else{
        EdittimePlan(this.editform).then(res => {
          if (res.data.code === 0) {
            this.SelectedData.forEach((value, index) => {
              value.weeks.sort()
              value['week'] = value.weeks.toString()
              value['timePlanId'] = this.editform.id
              value.timeFrameId = value.id
              // value.directions.sort()
              if (value.directions.length > 1) {
                value.directions = ["2"]
              }
              value['direction'] = value.directions.toString()
            })
            AddtimeframePlan(this.SelectedData).then(res => {
              if (res.data.code === 0) {
                this.$message.success('修改成功')
              }
              this.$router.go(-1)
            })
          } else {
            this.$message.error('修改失败')
          }
        })
      }
    },
    //取消
    dictItemVisible: function () {
      this.editform = {}
      this.$router.go(-1)
    },

    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange(current) {
      this.page.currentPage = current
    },

  }
}
</script>
<style scoped>
/deep/.avue-crud__menu{
  display: none;
}
/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 10px!important;
}
/deep/.avue-crud__pagination{
  display: none;
}
/deep/.el-card__body{
  padding: 15px;
}
.radio{
  margin-right: 12px;
  padding: 0;
}
h3{
  margin: 10px 0;
}
/deep/.direction .el-checkbox-button.is-checked .el-checkbox-button__inner{
  color: #FFFFFF !important;
  background-color: #67c23a !important;
  border-color: #fff !important;
  -webkit-box-shadow: -1px 0 0 0 #fff !important;
  box-shadow: -1px 0 0 0 #fff !important;
}
/deep/.direction span:hover{
  color: #67c23a!important;
}
/deep/.el-checkbox-button__inner{
  border: 1px solid #DCDFE6 !important;
}
</style>
